from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from bike.models import CollegeUser


class Command(BaseCommand):
    help = '为每个学院创建学院管理员用户'

    def add_arguments(self, parser):
        parser.add_argument(
            '--password',
            type=str,
            default='admin123456',
            help='默认密码（默认：admin123456）'
        )
        parser.add_argument(
            '--prefix',
            type=str,
            default='admin',
            help='用户名前缀（默认：admin）'
        )
        parser.add_argument(
            '--admin',
            action='store_true',
            default=True,
            help='是否为管理员（默认：是）'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='强制重新创建已存在的用户'
        )

    def handle(self, *args, **options):
        password = options['password']
        prefix = options['prefix']
        is_admin = options['admin']
        force = options['force']

        # 获取所有学院选择
        college_choices = CollegeUser._meta.get_field('college').choices
        
        self.stdout.write(
            self.style.SUCCESS(f'开始为 {len(college_choices)} 个学院创建管理员用户...')
        )
        
        created_count = 0
        skipped_count = 0
        error_count = 0

        for college_code, college_name in college_choices:
            username = f"{prefix}_{college_code}"
            
            try:
                # 检查用户是否已存在
                if User.objects.filter(username=username).exists():
                    if not force:
                        self.stdout.write(
                            self.style.WARNING(f'用户 {username} 已存在，跳过创建')
                        )
                        skipped_count += 1
                        continue
                    else:
                        # 删除已存在的用户
                        User.objects.filter(username=username).delete()
                        self.stdout.write(
                            self.style.WARNING(f'删除已存在的用户 {username}，重新创建')
                        )

                # 创建Django用户
                user = User.objects.create_user(
                    username=username,
                    password=password,
                    email=f'{username}@college.edu.cn',
                    first_name=college_name,
                    last_name='管理员'
                )
                
                # 创建学院用户
                college_user = CollegeUser.objects.create(
                    user=user,
                    college=college_code,
                    is_admin=is_admin,
                    is_super_admin=False  # 默认不是超级管理员
                )
                
                self.stdout.write(
                    self.style.SUCCESS(
                        f'✓ 成功创建: {username} - {college_name}'
                    )
                )
                created_count += 1
                
            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f'✗ 创建失败: {username} - {str(e)}')
                )
                error_count += 1

        # 输出统计信息
        self.stdout.write('\n' + '='*50)
        self.stdout.write(self.style.SUCCESS('创建完成！统计信息：'))
        self.stdout.write(f'  成功创建: {created_count} 个用户')
        self.stdout.write(f'  跳过创建: {skipped_count} 个用户')
        self.stdout.write(f'  创建失败: {error_count} 个用户')
        self.stdout.write('='*50)
        
        # 输出登录信息
        if created_count > 0:
            self.stdout.write('\n登录信息：')
            self.stdout.write(f'  用户名格式: {prefix}_<学院代码>')
            self.stdout.write(f'  密码: {password}')
            self.stdout.write('\n示例：')
            for college_code, college_name in college_choices[:3]:  # 只显示前3个示例
                username = f"{prefix}_{college_code}"
                self.stdout.write(f'  {username} - {college_name}')
            if len(college_choices) > 3:
                self.stdout.write(f'  ... 还有 {len(college_choices) - 3} 个学院用户')
